<template>
  <div class="mod-stock stock-list-mod">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"

        @submit.prevent
      >
        <!-- 表单项 -->
        <div class="input-row">
          <el-form-item :label="$t('takeStock.productFilter')+':'">
            <el-select
              v-model="searchForm.prodKeyType"
              @change="onProdKeyTypeChange"
            >
              <el-option
                v-for="node in prodKeyArr"
                :key="node.key"
                :label="node.label"
                :value="node.key"
              />
            </el-select>
            <el-input
              v-model="searchForm.prodKey"
              type="text"
              clearable
              :placeholder="prodKeyArr[searchForm.prodKeyType - 1].inputTips"
            />
          </el-form-item>
          <el-form-item :label="$t('product.productBrands')+':'">
            <el-select
              v-model="searchForm.brandId"
              clearable
              filterable
            >
              <el-option
                v-for="node in brandList"
                :key="node.brandId"
                :label="node.name"
                :value="node.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('product.shopCategories')+':'">
            <el-cascader
              v-model="selectedCategory"
              expand-trigger="hover"
              :options="categoryList"
              :props="categoryTreeProps"
              :clearable="true"
              @change="onHandleChange"
            />
          </el-form-item>
          <el-form-item :label="$t('product.stockWarning') + ':'">
            <el-select
              v-model="searchForm.isStockWarning"
              :placeholder="$t('product.stockWarning')"
              clearable
            >
              <el-option
                :label="$t('是')"
                :value="1"
              />
              <el-option
                :label="$t('否')"
                :value="2"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetForm()"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('multishop:inquireStock:export')"
          class="default-btn"
          @click="onExportSkuInfo"
        >
          {{ $t('order.ExportingFiles') }}
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-con">
        <el-table
          ref="dataListRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%;"
          :row-key="row => { return row.partyCode }"
          @selection-change="onSelectSome"
        >
          <el-table-column
            type="selection"
            align="center"
            fixed="left"
            width="55"
            :reserve-selection="true"
          />
          <el-table-column
            width="380"
            :label="$t('product.prodInfo')"
          >
            <template #default="scope">
              <div class="table-cell-con">
                <div class="table-cell-image">
                  <ImgShow :src="scope.row.pic" />
                </div>
                <div class="table-cell-text">
                  {{ scope.row.prodName }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('product.commodityCode')"
            width="240"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.partyCode }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="skuName"
            :label="$t('stock.spec')"
          >
            <template #default="scope">
              <div class="sku-name-txt">
                {{ scope.row.skuName || '-' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('coupon.stock')"
            prop="stocks"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.stocks }}</span>
            </template>
          </el-table-column>
          <el-table-column
            width="120px"
            :label="$t('stock.price')"
            prop="price"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('crud.menu')"
            fixed="right"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="default-btn text-btn"
                  @click="onQueryConditionHandle(scope.row)"
                >
                  {{ $t('stock.queryCondition') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分页 -->
    <el-pagination
      :current-page="page.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="page.pageSize"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="onPageSizeChange"
      @current-change="onPageChange"
    />
    <!-- 导出入库明细 -->
    <el-dialog
      v-model="exportStockBillLogVisible"
      :title="$t('formData.export')"
      top="25vh"
      width="500px"
    >
      <el-radio
        v-model="exportRadio"
        :label="1"
      >
        {{ $t('stock.exportOfSearchInquire') }}
      </el-radio>
      <el-radio
        v-model="exportRadio"
        :label="2"
      >
        {{ $t('stock.exportOfSelectInquire') }}
      </el-radio>
      <template #footer>
        <span

          class="dialog-footer"
        >
          <div
            class="default-btn"
            @click="exportStockBillLogVisible = false"
          >{{ $t('crud.filter.cancelBtn') }}</div>
          <div
            class="default-btn primary-btn"
            @click="onConfirmExport"
          >{{ $t('crud.filter.submitBtn') }}</div>
        </span>
      </template>
    </el-dialog>
    <stock-inquire-dialog
      v-if="inquireDialogVisible"
      ref="inquireDialogRef"
    />
  </div>
</template>

<script setup>
import { treeDataTranslate, isAuth } from '@/utils'
import stockInquireDialog from '../../components/stock-inquire-dialog.vue'
import { ElMessage, ElLoading } from 'element-plus'

// eslint-disable-next-line vue/require-prop-types
const props = defineProps(['isStockWarning'])

let tempSearchForm = null // 保存上次点击查询的请求条件

let isSubmit = false
const dataList = ref([]) // 表格数据
const inquireDialogVisible = ref(false) // 查看同款信息弹窗
const exportStockBillLogVisible = ref(false) // 导出弹窗是否可见
const exportRadio = ref(1) //  1 按搜索条件导出 2 按选择项导出
let dataListSelections = [] // 已选择的数据项
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const prodKeyArr = [
  { key: 1, label: $t('product.prodName'), inputTips: $t('takeStock.inputName') },
  { key: 2, label: $t('product.commodityCode'), inputTips: $t('takeStock.inputPartyCode') }
]
const brandList = ref([])
const categoryList = ref([])
const selectedCategory = ref([])
const searchForm = reactive({
  prodKeyType: 1, // 1：商品名称 2：商品编码
  isCompose: 0, // 是否组合商品
  prodKey: '', // 搜索商品关键词
  brandId: null, // 品牌id
  shopCategoryId: null, // 店铺分类id
  isStockWarning: null // 库存预警
})
const categoryTreeProps = reactive({
  value: 'categoryId',
  label: 'categoryName'
})
onMounted(() => {
  searchForm.isStockWarning = props.isStockWarning
  init()
})

const init = () => {
  selectedCategory.value = []
  getDataList()
  // 获取品牌列表
  getBrandList()
  // 获取分类列表
  getCategoryList()
}
const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/sku/pageSku'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
  }).catch(() => {
  })
}
const onProdKeyTypeChange = () => {
  searchForm.prodKey = ''
}
const getBrandList = () => {
  http({
    url: http.adornUrl('/admin/brand/listSigningBrand'),
    method: 'get',
    params: http.adornParams({
      status: 1 // 签约审核 0 未审核 1已通过 -1未通过
    })
  }).then(({ data }) => {
    brandList.value = data.platformBrandList
  })
}
const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get'
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}
/**
 * 获取分类id
 */
const onHandleChange = (val) => {
  if (Array.isArray(val)) {
    searchForm.shopCategoryId = val[val.length - 1] || null
  } else {
    searchForm.shopCategoryId = val
  }
}
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(null, newData)
}
const onExportSkuInfo = () => {
  exportStockBillLogVisible.value = true
}
const onResetForm = () => {
  searchForm.prodKeyType = 1 // 1：商品名称 2：商品编码
  searchForm.prodKey = '' // 搜索商品关键词
  searchForm.supplierId = null // 供应商id
  searchForm.brandId = null // 品牌id
  searchForm.shopCategoryId = null // 店铺分类id
  searchForm.isStockWarning = null // 库存预警

  selectedCategory.value = []
}
const inquireDialogRef = ref(null)
const onQueryConditionHandle = (row) => {
  inquireDialogVisible.value = true
  nextTick(() => {
    inquireDialogRef?.value.init(row.prodId)
  })
}
const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList(page)
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList(page)
}
// 多选变化
const onSelectSome = (val) => {
  dataListSelections = val
}
/**
 * 确定导出
 */
const onConfirmExport = () => {
  if (exportRadio.value !== 1 && exportRadio.value !== 2) {
    ElMessage({
      message: $t('stock.exportRadioEmptyTips'),
      type: 'error',
      duration: 1500,
      onClose: () => {
        isSubmit = false
      }
    })
    return
  }
  if (isSubmit) {
    return
  }
  isSubmit = true
  // 准备参数
  let params = {}
  if (exportRadio.value === 1) {
    // 导出模式为按搜索条件导出
    if (page.total === 0) {
      ElMessage({
        message: $t('stock.exportStockLogSearchEmptyTips'),
        type: 'error',
        duration: 1500,
        onClose: () => {
          isSubmit = false
        }
      })
      return
    }
    params = tempSearchForm
    params.skuIds = null
  } else {
    // 导出模式为按选中的数据导出
    if (dataListSelections.length === 0) {
      ElMessage({
        message: $t('stock.exportStockLogSelectEmptyTips'),
        type: 'error',
        duration: 1500,
        onClose: () => {
          isSubmit = false
        }
      })
      return
    }
    params.skuIds = dataListSelections.map(item => {
      return item.skuId
    })
  }
  const loading = ElLoading.service({
    lock: true,
    target: '.stock-list-mod',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('formData.exportIng')
  })
  http({
    url: http.adornUrl('/sku/exportSkuList'),
    method: 'get',
    params: http.adornParams(params),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('stock.skuStockXls')
    const elink = document.createElement('a')
    if ('download' in elink) {
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      navigator.msSaveBlob(blob, fileName)
    }
    ElMessage({
      message: $t('stock.exportSuccess'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        isSubmit = false
        exportStockBillLogVisible.value = false
      }
    })
  }).catch((e) => {
    loading.close()
    isSubmit = false
  })
}

</script>
